//
//  YBFindPasswordViewController.m
//  ZhongWangYuanApp
//
//  Created by apple on 2019/1/2.
//  Copyright © 2019年 apple. All rights reserved.
//

#import "YBFindPasswordViewController.h"
#import "ZJAdditions.h"
//#import "NetWorkingManager.h"
#import "UIButton+countDown.h"
#import "ZJTabBarController.h"
//#import "ZJReportViewController.h"
//#import "ZJUserRegisterInfoModel.h"
//#import "LPChooseReportTypeViewController.h"
#import "YBLoginViewController.h"
#import "HomeMenuViewController.h"
#import "ElectiveViewController.h"
#import "YBElectiveViewController.h"

#import "SubjectViewController.h"
#import "MyViewController.h"
@interface YBFindPasswordViewController ()<UITextFieldDelegate , UITabBarControllerDelegate>

/** 姓名 */
@property (nonatomic, strong) UITextField *password;
/** 安全码 */
@property (nonatomic, strong) UITextField *safe;
/** 安全码图片 */
@property (nonatomic, strong) UIImageView *safeImageView;
/** 手机号码 */
@property (nonatomic, strong) UITextField *phoneNumber;
/** 验证码 */
@property (nonatomic, strong) UITextField *verification;
/** 获取验证码 */
@property (nonatomic, strong) UIButton *verificationButton;
/** 注册 */
@property (nonatomic, strong) UIButton *userRegist;
@end

@implementation YBFindPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"找回密码";
    [self setupUI];
    self.phoneNumber.text = self.phoneString;
    //    [self.safeImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@api/VerifyCode/activeyzmcode/%.0lf" , HTMLURL , ([[NSDate date] timeIntervalSince1970] * 1000)]]];
    [YBRequestManager request_sessionIdWithSuccessBlock:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            [[NSUserDefaults standardUserDefaults] setObject:object[@"data"][@"sessionId"] forKey:@"sessionId"];
        }
    } failBlock:^(id object) {
        
    }];
}
- (void)setupUI{
    //    [self.view addSubview:self.safe];
    //    [self.view addSubview:self.safeImageView];
    [self.view addSubview:self.phoneNumber];
    [self.view addSubview:self.verification];
    [self.view addSubview:self.verificationButton];
    [self.view addSubview:self.password];
    [self.view addSubview:self.userRegist];
    
    //姓名提示
    UILabel *passwordLabel = [UILabel new];
    passwordLabel.text = @"新密码 :";
    passwordLabel.textColor = [UIColor textBlackColor];
    passwordLabel.font = [UIFont titleTextFont];
    
    //姓名提示
    //    UILabel *safeLabel = [UILabel new];
    //    safeLabel.text = @"安全码 :";
    //    safeLabel.textColor = [UIColor textBlackColor];
    //    safeLabel.font = [UIFont titleTextFont];
    
    //手机号提示
    UILabel *phoneLabel = [UILabel new];
    phoneLabel.text = @"手机号 :";
    phoneLabel.textColor = [UIColor textBlackColor];
    phoneLabel.font = [UIFont titleTextFont];
    //验证码提示
    UILabel *VLabel = [UILabel new];
    VLabel.text = @"验证码 :";
    VLabel.textColor = [UIColor textBlackColor];
    VLabel.font = [UIFont titleTextFont];
    [self.view addSubview:passwordLabel];
    //    [self.view addSubview:safeLabel];
    [self.view addSubview:phoneLabel];
    [self.view addSubview:VLabel];
    
    
    NSString * detailString = @"密码长度必须大于6位。";
    UILabel * detailLabel = [ToolClass creatLabelWithFrame:CGRectMake(0, 0, 1, 1) font:[UIFont subTitleTextFontSize] textColor:[UIColor textGrayColor] text:detailString];
    
    CGFloat detailHeight = [detailString boundingRectWithSize:CGSizeMake([UIScreen zj_screenWith] - 54 * [UIScreen zj_screenWScale], CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName     : [UIFont subTitleTextFont]} context:nil].size.height;
    
    [self.view addSubview:detailLabel];
    
    
    //    safeLabel.sd_layout
    //    .topSpaceToView(self.password, 23 * [UIScreen zj_screenHScale])
    //    .leftEqualToView(self.password)
    //    .rightEqualToView(self.password)
    //    .heightIs([NSString heightWithTextFontSize:[UIFont titleTextFontSize]]);
    //
    //    self.safeImageView.sd_layout
    //    .topSpaceToView(safeLabel, 11 * [UIScreen zj_screenHScale])
    //    .rightEqualToView(safeLabel)
    //    .widthIs(100 * [UIScreen zj_screenWScale])
    //    .heightRatioToView(self.password, 1);
    //
    //    self.safe.sd_layout
    //    .topEqualToView(self.safeImageView)
    //    .leftEqualToView(safeLabel)
    //    .rightSpaceToView(self.safeImageView, 12 * [UIScreen zj_screenWScale])
    //    .heightRatioToView(self.safeImageView, 1);
    
    phoneLabel.sd_layout
    .topSpaceToView(self.navigView,25 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .heightIs([NSString heightWithTextFontSize:[UIFont titleTextFontSize]]);
    
    self.verificationButton.sd_layout
    .topSpaceToView(phoneLabel, 11 * [UIScreen zj_screenHScale])
    .rightEqualToView(phoneLabel)
    .widthIs(100 * [UIScreen zj_screenWScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    self.phoneNumber.sd_layout
    .topSpaceToView(phoneLabel, 11 * [UIScreen zj_screenHScale])
    .leftEqualToView(phoneLabel)
    .rightSpaceToView(self.verificationButton, 12 * [UIScreen zj_screenWScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    
    
    VLabel.sd_layout
    .topSpaceToView(self.phoneNumber, 23 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.phoneNumber)
    .rightEqualToView(self.phoneNumber)
    .heightIs([NSString heightWithTextFontSize:[UIFont titleTextFontSize]]);
    
    self.verification.sd_layout
    .topSpaceToView(VLabel, 11 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .heightRatioToView(self.phoneNumber, 1);
    
    
    passwordLabel.sd_layout
    .topSpaceToView(self.verification,23 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .heightIs([NSString heightWithTextFontSize:[UIFont titleTextFontSize]]);
    
    self.password.sd_layout
    .topSpaceToView(passwordLabel, 11 * [UIScreen zj_screenHScale])
    .leftEqualToView(passwordLabel)
    .rightEqualToView(passwordLabel)
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    detailLabel.sd_layout
    .topSpaceToView(self.password, 23 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale] - 1)
    .heightIs(detailHeight + 1);
    
    self.userRegist.sd_layout
    .bottomSpaceToView(self.view, ItemHeight * 75)
    .leftSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 27 * [UIScreen zj_screenWScale])
    .heightRatioToView(self.password, 1);
}


- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([viewController isKindOfClass:[HomeMenuViewController class]]) {
        return YES;
    }else if ([viewController isKindOfClass:[YBElectiveViewController class]]) {
        return [self isLoging];
    }else if ([viewController isKindOfClass:[SubjectViewController class]]) {
        return  [self isLoging];
    }else if ([viewController isKindOfClass:[MyViewController class]]) {
        return [self isLoging];
    }
    return YES;
}

- (BOOL)isLoging{
    if (YBUSERINFOMODEL.studentId.length > 0) {
        return YES;
    }else{//未登录
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请先登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            YBLoginViewController *vc = [YBLoginViewController new];
            [[ToolClass getMainNavigationController] pushViewController:vc animated:YES];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[ToolClass getMainNavigationController] presentViewController:alertController animated:YES completion:nil];
        
        return NO;
    }
}



#pragma mark - 点击事件
/** 发送验证码 */
- (void)action_sendVerification{
    [self.password resignFirstResponder];
    [self.phoneNumber resignFirstResponder];
    [self.verification resignFirstResponder];
    if (self.phoneNumber.text.length == 0) {
        [YJProgressHUD showMsgWithoutView:@"请输入的手机号码"];
        return;
    }
    if (![CManager zj_validateMobile:self.phoneNumber.text]) {
        [YJProgressHUD showMsgWithoutView:@"请输入正确的手机号码"];
        return;
    }
    [YJProgressHUD showMessage:@"正在发送..." duration:10 view:self.view];
    [YBRequestManager request_sendVerifySMSCodeWithPhone:self.phoneNumber.text successBlock:^(id object) {
        [YJProgressHUD hide];
        if ([object[@"code"] integerValue] == 1) {
            [self.verificationButton startWithTime:60 title:@"重新获取" countDownTitle:@"重新获取" mainColor:[UIColor textBlackColor] countColor:[UIColor textBlackColor]];
        }
        else{
            [YJProgressHUD showMsgWithoutView:@"获取失败"];
        }
    } failBlock:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"获取失败"];
    }];
    
}



/** 注册 */
- (void)action_userRegist{
    [self.view endEditing:YES];

    if (self.phoneNumber.text.length == 0) {
        [YJProgressHUD showMsgWithoutView:@"请输入的手机号码"];
        return;
    }
    if (![CManager zj_validateMobile:self.phoneNumber.text]) {
        [YJProgressHUD showMsgWithoutView:@"请输入正确的手机号码"];
        return;
    }
    if (self.verification.text.length == 0) {
        [YJProgressHUD showMsgWithoutView:@"请输入的短信验证码"];
        return;
    }
    if (self.password.text.length < 6) {
        [YJProgressHUD showMessage:@"密码长度必须大于6位" inView:self.view afterDelayTime:2.f];
        return;
    }
    //输入的信息都正确
    [YJProgressHUD showMessage:@"操作中..." duration:30 view:self.view];
    [YBRequestManager request_findPasswordWithCellphone:self.phoneNumber.text password:self.password.text inputsmscode:self.verification.text successBlock:^(id object) {
        [YJProgressHUD hide];
        if([object[@"code"] integerValue] == 1) {
            if ([object[@"data"][@"result"] integerValue] == 1 && [object[@"data"][@"index"] integerValue] == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            else{
                [YJProgressHUD showMsgWithoutView:[NSString stringWithFormat:@"%@" , object[@"data"][@"message"]]];
            }
        }
        else{
            [YJProgressHUD showMsgWithoutView:@"操作失败"];
        }
    } failBlock:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"操作失败"];
    }];
    
}


#pragma mark - UITextFieldDelegate 协议方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.phoneNumber) {
        if (toBeString.length >= 11 && range.length!=1){
            textField.text = [toBeString substringToIndex:11];
            return NO;
            
        }
    }else if (textField == self.verification) {
        if (toBeString.length >= 6 && range.length!=1){
            textField.text = [toBeString substringToIndex:6];
            return NO;
            
        }
    }
    
    return YES;
}


-(void)option_tapSafeImageWithGesture:(UITapGestureRecognizer *)gesture{
    [self.safeImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@api/VerifyCode/activeyzmcode/%.0lf" , HTMLURL , ([[NSDate date] timeIntervalSince1970] * 1000)]]];
}

#pragma mark - Setter
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    return YES;
}

#pragma mark - Getters

- (UITextField *)password{
    if (_password == nil){
        _password = [[UITextField alloc]init];
        _password.placeholder = @"请输入至少6位的新密码";
        _password.secureTextEntry = YES;
        _password.textColor = [UIColor textBlackColor];
        _password.font = [UIFont titleTextFont];
        [_password setTextFieldLeftforWidth:14 * [UIScreen zj_screenWScale]];
        [_password setTextFieldRightforWidth:14 * [UIScreen zj_screenWScale]];
        _password.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _password.layer.borderWidth = 1.0;
        _password.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _password.returnKeyType = UIKeyboardTypeTwitter;
        _password.delegate = self;
    }
    return _password;
}


- (UITextField *)safe{
    if (_safe == nil){
        _safe = [[UITextField alloc]init];
        _safe.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _safe.placeholder = @"请输入右侧的安全码";
        _safe.textColor = [UIColor textBlackColor];
        _safe.font = [UIFont titleTextFont];
        [_safe setTextFieldLeftforWidth:14 * [UIScreen zj_screenWScale]];
        [_safe setTextFieldRightforWidth:14 * [UIScreen zj_screenWScale]];
        _safe.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _safe.layer.borderWidth = 1.0;
        _safe.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _safe.returnKeyType = UIKeyboardTypeTwitter;
        _safe.delegate = self;
    }
    return _safe;
}


- (UIImageView *)safeImageView{
    if (_safeImageView == nil){
        _safeImageView = [[UIImageView alloc]init];
        _safeImageView.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        _safeImageView.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _safeImageView.layer.borderWidth = 1.0;
        _safeImageView.clipsToBounds = YES;
        _safeImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(option_tapSafeImageWithGesture:)];
        [_safeImageView addGestureRecognizer:tapGesture];
    }
    return _safeImageView;
}

- (UITextField *)phoneNumber{
    if (_phoneNumber == nil){
        _phoneNumber = [[UITextField alloc]init];
        _phoneNumber.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _phoneNumber.placeholder = @"请输入手机号";
        _phoneNumber.textColor = [UIColor textBlackColor];
        _phoneNumber.font = [UIFont titleTextFont];
        [_phoneNumber setTextFieldLeftforWidth:14 * [UIScreen zj_screenWScale]];
        [_phoneNumber setTextFieldRightforWidth:14 * [UIScreen zj_screenWScale]];
        _phoneNumber.delegate = self;
        _phoneNumber.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _phoneNumber.layer.borderWidth = 1.0;
        _phoneNumber.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _phoneNumber.returnKeyType = UIKeyboardTypeTwitter;
        
    }
    return _phoneNumber;
}

- (UITextField *)verification{
    if (_verification  == nil){
        _verification = [[UITextField alloc]init];
        _verification.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _verification.placeholder = @"请输入手机验证码";
        _verification.textColor = [UIColor textBlackColor];
        _verification.font = [UIFont titleTextFont];
        [_verification setTextFieldLeftforWidth:14 * [UIScreen zj_screenWScale]];
        _verification.delegate = self;
        [_verification setTextFieldRightforWidth:14 * [UIScreen zj_screenWScale]];
        _verification.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _verification.layer.borderWidth = 1.0;
        _verification.sd_cornerRadius = @(4 * [UIScreen zj_screenHScale]);
        _verification.returnKeyType = UIKeyboardTypeTwitter;
        
    }
    return _verification;
}

- (UIButton *)verificationButton{
    if (_verificationButton == nil){
        _verificationButton = [[UIButton alloc]init];
        [_verificationButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_verificationButton setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
        _verificationButton.titleLabel.font = [UIFont systemFontOfSize:15 * [UIScreen zj_textFontScale]];
        _verificationButton.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        _verificationButton.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _verificationButton.layer.borderWidth = 1.0;
        [_verificationButton addTarget:self action:@selector(action_sendVerification) forControlEvents:UIControlEventTouchUpInside];
    }
    return _verificationButton;
}
- (UIButton *)userRegist{
    if (_userRegist == nil){
        _userRegist = [[UIButton alloc]init];
        [_userRegist setTitle:@"确认" forState:UIControlStateNormal];
        [_userRegist setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _userRegist.backgroundColor = [UIColor themeColor];
        _userRegist.titleLabel.font = [UIFont titleTextFont];
        _userRegist.layer.cornerRadius = 4 * [UIScreen zj_screenHScale];
        [_userRegist addTarget:self action:@selector(action_userRegist) forControlEvents:UIControlEventTouchUpInside];
    }
    return _userRegist;
}


@end
